package com.bjsxt.userscenter.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.common.util.HttpUtil;

/**
 * 需要登陆的Servlet
 * 
 * @author WangshSxt
 *
 */
public class AuthFilter implements Filter
{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException
	{

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException
	{
		System.out.println("=========doFilter=======");
		
		HttpServletRequest request = (HttpServletRequest) req ; 
		HttpServletResponse response = (HttpServletResponse) res ;
		HttpSession session = request.getSession() ; 
		
		/* 先检查session是否有值 */
		JSONObject adminsJSON = (JSONObject) session.getAttribute("admins");
		if(adminsJSON != null)
		{
			chain.doFilter(request, response);
			return ; 
		}
		
		/* token
		 * 如果有多个token:
		 * 取最后一个
		 *  */
		String[] tokens = request.getParameterValues("token");
		String token = "" ; 
		if(tokens != null)
		{
			token = tokens[tokens.length - 1]; 
		}
		
		/* 传入了token
		 * 就是从用户中心跳转过来的
		 *  */
		if(!"".equalsIgnoreCase(token))
		{
			/* 到token的颁发中心,去验证一下是不是你颁发的
			 * 验证token的接口,我们今天上午写过了
			 *  */
			HttpUtil httpUtil = new HttpUtil() ;
			
			/*
			 * 拼装上行的json
			 */
			JSONObject requestJSON = new JSONObject() ; 
			requestJSON.put("version", "1");
			
			JSONObject dataJSON = new JSONObject() ; 
			dataJSON.put("token", token);
			
			requestJSON.put("data", dataJSON);
			
			/* 拼装url */
			/*String url = "http://localhost:8080/userscenter-back/outer/json/verfiyToken.htm?json={%22version%22:%221%22,%22data%22:{%22token%22:%2226174d6f-2cac-4a00-99ff-7d79df12f38a%22}}" ;*/
			String url = ConstatFinalUtil.CONFIG_JSON.getString("userscenter.back.verifyToken.url");
			String params = "?json=" + requestJSON.toJSONString() ;
			url += params ;
			System.out.println("-----url----------" + url);
			String result = httpUtil.methodGet(url);
			System.out.println(result + "==============");
			/*
			 * 处理返回值
			 * 解析成json
			 *  */
			JSONObject resultJSON = (JSONObject) JSON.parse(result);
			/*
			 * code:0成功
			 * */
			if(resultJSON != null && "0".equalsIgnoreCase(resultJSON.getString("code")))
			{
				chain.doFilter(request, response);
				return ;
			}
		}
		
		/* 需要登陆
		 * 获取当前访问的URL
		 * 客户端跳转到用户中心的登陆页面,
		 * 把returnUrl带上,同时要加密哟(UrlEncode)
		 *  */
		String returnUrl = request.getRequestURL() + ""; 
		String queryStr = request.getQueryString() ; 
		/*?后面的参数木有了,
		 * 如何获取呢? 
		 * */
		if(queryStr != null)
		{
			returnUrl += "?" + queryStr ; 
		}
		System.out.println("=====returnUrl==========" + returnUrl);
		/*
		 * 客户端中转到用户中心
		 * http://xxxx:8080/userscenter-back/login.htm?returnUrl
		 * */
		String url = ConstatFinalUtil.CONFIG_JSON.getString("userscenter.back.login.url") ;
		url += "&returnUrl=" + URLEncoder.encode(returnUrl,"UTF-8") ; 
		System.out.println("=====url========" + url);
		response.sendRedirect(url);
	}

	@Override
	public void destroy()
	{

	}

}
